import 'dart:typed_data';
import 'dart:ui';

import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:gd_assistant/api/apiHandler.dart';
import 'package:gd_assistant/globalConfig.dart';
import 'package:gd_assistant/main.dart';
import 'package:gd_assistant/model/userModel.dart';
import 'package:gd_assistant/page/me/changePassWordPage.dart';
import 'package:gd_assistant/page/public/colors.dart';
import 'package:gd_assistant/page/public/publicView.dart';
import 'package:gd_assistant/page/public/themeUtils.dart';
import 'package:gd_assistant/util/customRoute.dart';
import 'package:gd_assistant/util/dataUtil.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';

class myCardPage extends StatefulWidget {
  @override
  _myCardPageState createState() => _myCardPageState();
}

class _myCardPageState extends State<myCardPage> {
  bool isDark = false;
  GlobalKey rootWidgetKey = GlobalKey();
  String avatar = "";
  String name = "";
  String nickName = "";
  String qrCode = "";
  String motto = "";

  //截组件图片
  _capturePng() async {
      PermissionStatus permission = await PermissionHandler().checkPermissionStatus(PermissionGroup.storage);
     if (permission == PermissionStatus.granted) { 
          try {
            RenderRepaintBoundary boundary =
                rootWidgetKey.currentContext.findRenderObject();
            var image = await boundary.toImage(pixelRatio: 3.0);
            ByteData byteData = await image.toByteData(format: ImageByteFormat.png);
            Uint8List pngBytes = byteData.buffer.asUint8List();
            TostUtil.showLoading(context, "图片保存中");                
            final result = await ImageGallerySaver.saveImage(pngBytes);
            TostUtil.removeLoading(context); 
            if (result.toString() != '') {
              TostUtil.show("保存成功");
            }else {
              TostUtil.show("保存失败");
            }
          } catch (e) {
            print(e);
          }
    } else {
        PermissionHandler().requestPermissions(<PermissionGroup>[
        PermissionGroup.storage, // 在这里添加需要的权限
      ]);
    }
   
  }

  Widget header() {
    return Container(
      margin: EdgeInsets.all(20),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(8),
          child: Container(
            height: 520,
            color: Colors.blue,
            child: Column(
              children: [
                Expanded(
                  flex: 1,
                  child: Column(
                    children: [
                      Container(
                        padding: EdgeInsets.fromLTRB(12, 12, 12, 56),
                        child: Row(
                          children: [
                            Image.asset(
                              "images/logo.png",
                              height: 30,
                              width: 30,
                              fit: BoxFit.cover,
                            ),
                            Padding(
                              padding: EdgeInsets.only(left:8),
                              child: Text("河马医疗", style: TextStyle(color: Colors.white, fontSize: 18),
                            )),
                          ],
                        ),
                      ),
                      ClipRRect(
                        child: ExtendedImage.network(
                            GlobalConfig.qiNiuUri + (avatar != null ? avatar : ""),
                            width: 100,
                            height: 100,
                            fit: BoxFit.cover,
                            shape: BoxShape.rectangle,
                            border: Border.all(color: Colors.white, width: 2),
                            borderRadius: BorderRadius.all(Radius.circular(8.0)),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.only(top:12),
                        child: Text("医生助理", style: TextStyle(color: Colors.white, fontSize: 20),
                      )),
                      Padding(
                        padding: EdgeInsets.only(top:6),
                        child: Text(name, style: TextStyle(color: Colors.white, fontSize: 28, fontWeight: FontWeight.w600),
                      )),
                      Padding(
                        padding: EdgeInsets.only(top:6),
                        child: Text(nickName, style: TextStyle(color: Colors.white, fontSize: 18),
                      ))
                    ],
                  )
                ),
                Container(
                  height: 160,
                  color: Colors.white,
                  child: Row(
                    children: [
                      Padding(
                        padding: EdgeInsets.only(left: 28,right: 20),
                        child: ExtendedImage.network(
                          GlobalConfig.qiNiuUri + (qrCode != null ? qrCode : ""),
                          height: 100,
                          width: 100,
                          fit: BoxFit.cover
                      )),
                      Expanded(
                        child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Padding(
                            padding: EdgeInsets.only(right:28),
                            child:   Text(motto, style: TextStyle(fontSize: 16)),
                          ),
                          Padding(
                            padding: EdgeInsets.only(top:10),
                            child: Text(
                              "微信识别二维码", 
                              style: TextStyle(color: Colors.grey, fontSize: 16),
                          ))
                        ],
                      )
                      )
          
                    ],
                  ),
                )
                
              ],
            )
        ),
      ),
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    loadData();
  }

  loadData() async {
    Assistant cb = await apiHandler.getAssistantInfo();
    if (cb != null) {
      avatar = cb.avatar != null ? cb.avatar : "";
      name = cb.name != null ? cb.name : "";
      nickName = cb.nickName != null ? cb.nickName : "";
      qrCode = cb.qrCode != null ? cb.qrCode : "";
      motto = cb.motto != null ? cb.motto : "";
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    isDark = ThemeUtils.isDark(context);
    Color bg_color = isDark ? Colours.dark_bg_gray : Colors.white;
    return Scaffold(
      backgroundColor: isDark ? Colours.dark_bg_color : Colours.bg_color,
      appBar: AppBar(
        title: Text("我的名片"),
      ),
      body: Container(
        child: Column(
          children: [
            RepaintBoundary(
              key: rootWidgetKey,
              child: header(),
            ),
            ZLButton(title: "保存名片到相册", onTap: (){
              _capturePng();
            })
          ],
        ),
      ),
    );
  }
}